package org.infodavid.common.util;

/**
 * The Class AbstractProcessor.
 */
public abstract class AbstractProcessor {

  /**
   * The property name used to set the retry count when invoking operations.
   */
  public static final String RETRY_COUNT_SYSTEM_PROPERTY = "org.infodavid.processor.retryCount";

  /** The default retry count. */
  public static final int DEFAULT_CLIENT_RETRY_COUNT = 3;

  /**
   * The property name used to set the retry period when invoking operations.
   */
  public static final String RETRY_PERIOD_SYSTEM_PROPERTY = "org.infodavid.processor.retryPeriod";

  /** The default retry period. */
  public static final long DEFAULT_CLIENT_RETRY_PERIOD = 1000;

  /** The failOnError flag. */
  private boolean failOnError = true;

  /**
   * Instantiates a new processor.
   */
  protected AbstractProcessor() {
    super();
  }

  /**
   * Gets the retry countproperty.
   * @return the retry countproperty
   */
  protected String getRetryCountProperty() {
    return RETRY_COUNT_SYSTEM_PROPERTY;
  }

  /**
   * Gets the client retry count.
   * @return the retry count
   */
  public final int getRetryCount() {
    final String value = System.getProperty(getRetryCountProperty());
    int result = DEFAULT_CLIENT_RETRY_COUNT;

    if (StringUtils.isNotEmpty(value)) {
      try {
        result = Double.valueOf(value).intValue();
      }
      catch (final Exception e) {
        result = -1;
      }
    }

    if (result < 0) {
      result = DEFAULT_CLIENT_RETRY_COUNT;
    }

    return result;
  }

  /**
   * Gets the retry period property.
   * @return the retry period property
   */
  protected String getRetryPeriodProperty() {
    return RETRY_PERIOD_SYSTEM_PROPERTY;
  }

  /**
   * Gets the client retry period.
   * @return the retry period
   */
  public final long getRetryPeriod() {
    final String value = System.getProperty(getRetryPeriodProperty());
    long result = DEFAULT_CLIENT_RETRY_PERIOD;

    if (StringUtils.isNotEmpty(value)) {
      try {
        result = Double.valueOf(value).longValue();
      }
      catch (final Exception e) {
        result = -1;
      }
    }

    if (result < 0) {
      result = DEFAULT_CLIENT_RETRY_PERIOD;
    }

    return result;
  }

  /**
   * Sets the fail on error.
   * @param flag the new fail on error
   */
  public void setFailOnError(final boolean flag) {
    failOnError = flag;
  }

  /**
   * Checks if is fail on error.
   * @return true, if is fail on error
   */
  public boolean isFailOnError() {
    return failOnError;
  }
}
